import './ItemOperate.scss';

import React, {
  FC,
  ReactElement,
  useRef,
  useCallback,
  useMemo
} from 'react';
import {
  Spin,
  Form,
  Button,
  Skeleton,
} from '@douyinfe/semi-ui';
import { IconUpload } from '@douyinfe/semi-icons';
import type { FormApi } from '@douyinfe/semi-ui/lib/es/form';
import type { FileItem } from '@douyinfe/semi-ui/lib/es/upload';
import { readImgFileSrc } from '@/utils/tools';
import type { FieldsCityInfo } from '../types';

interface IProps {
  loading?: boolean;
  type: 'add' | 'edit';
  data: Partial<FieldsCityInfo> & { id?: number | string };
  onCancel: () => void | Promise<void>;
  onSubmit: (formData: Partial<FieldsCityInfo>) => void | Promise<void>;
}

const FieldsCitiesItemOperate: FC<IProps> = (props): ReactElement => {
  const {
    loading,
    type,
    data,
    onCancel,
    onSubmit
  } = props;

  const formApiRef = useRef<FormApi<Record<string, any>>>(null);

  const initValues = useMemo(() => {
    if (type === 'edit') {
      const initFormData: Partial<FieldsCityInfo> & { imgList?: FileItem[] } = {
        ...data
      };
      const { img } = data;
      const imgList: FileItem[] = img
        ? [{
          url: img,
          name: 'banner.png',
          status: 'success',
          uid: String(data.createTime || Date.now()),
          size: '4.5MB',
          preview: true,
        }]
        : [];
      initFormData.imgList = imgList;
      return initFormData;
    }
    return {};
  }, [type, data]);

  const handleSubmitClick = useCallback(async () => {
    if (!formApiRef.current) return;
    const formApi = formApiRef.current;

    // 1. 校验
    await formApi.validate();

    // 2. 收集数据
    const formValues = formApi.getValues();
    const imgList: FileItem[] = formValues?.imgList ?? [];
    let img: string;

    if (imgList[0].fileInstance) {
      img = await (!imgList[0] ? '' : readImgFileSrc(imgList[0].fileInstance));
    } else {
      // 如果上传了新的图片，则使用新的图片，否则使用原来的图片
      img = formValues.img;
    }

    formValues.img = img;

    if (type === 'edit') {
      formValues.id = data.id;
    }

    delete formValues.imgList;

    // 3. 提交内容
    await onSubmit?.(formValues);
    onCancel?.();
  }, [formApiRef.current, data.id, type, onSubmit, onCancel]);

  return (
    <div className="fields-cities-item-operate">
      <Spin spinning={loading}>
        {(type === 'edit' && !!loading)
          ? (<Skeleton />)
          : (
            <Form
              layout="vertical"
              initValues={initValues}
              getFormApi={formApi => formApiRef.current = formApi}
              labelPosition="left"
              labelAlign="right"
              labelWidth="150px"
            >
              <Form.Input
                field="name"
                label="城市简称"
                placeholder="请填写城市简称（注意, 不能重复!）"
                style={{ width: 600 }}
                rules={[
                  {
                    required: true,
                    validator: (r, val, cb) => {
                      if (typeof val !== 'string' || !val.length) {
                        cb('城市简称不能为空');
                        return false;
                      }
                      cb();
                      return true;
                    }
                  },
                ]}
              />
              <Form.Input
                field="aliasName"
                label="城市全称"
                placeholder="请填写城市全称"
                style={{ width: 600 }}
                rules={[
                  { required: true, message: '城市全称不能为空' }
                ]}
              />
              <Form.Upload
                field="imgList"
                label="城市封面"
                action="#"
                multiple={false}
                // draggable
                defaultFileList={initValues.imgList ?? []}
                uploadTrigger="custom"
                beforeUpload={() => false}
                style={{ width: 600 }}
                rules={[
                  {
                    required: true,
                    validator: (r, val, cb) => {
                      if (!val?.length) {
                        cb('城市封面不能为空');
                        return false;
                      }
                      cb();
                      return true;
                    }
                  }
                ]}
              >
                <Button icon={<IconUpload />}>点击上传</Button>
              </Form.Upload>
              <Form.TextArea
                field="description"
                label="城市描述"
                placeholder="请填写城市描述"
                maxLength={500}
                style={{ width: 600 }}
              />
            </Form>
          )
        }
      </Spin>
      <footer className="btn-group">
        <Button onClick={onCancel}>取消</Button>
        <Button
          theme="solid"
          type="primary"
          loading={loading}
          onClick={handleSubmitClick}
        >
          确定
        </Button>
      </footer>
    </div>
  );
}

export default FieldsCitiesItemOperate;
